<template>
  <div class="content">
      <span>MyInfo:</span>
      <p>Name: {{name}}, Age: {{age}}</p>
      <div>
          <input v-model="name" type="text" placeholder="请输入新的姓名">
          <input v-model="age" type="number" placeholder="请输入新的年龄">
          <button @click="update">Update</button>
      </div>
  </div>
</template>

<<script>
    import Web3 from 'web3'
    import contract from 'truffle-contract'
    import artifacts from '../../build/contracts/UserInfo.json'
    const UserInfoContract = contract(artifacts)

    export default {
        name: 'UserInfo',
        data() {
            return {
                account: null,
                name: null,
                age: null
            }
        },
        created() {
            if (typeof web3 !== 'undefined') {
                web3 = new Web3(web3.currentProvider)
            } else {
                web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"))
            }
            UserInfoContract.setProvider(web3.currentProvider)
            this.account = web3.eth.coinbase;
            console.log(this.account);
            UserInfoContract.deployed().then((instance) => {
                instance.getName().then((name) => this.name = name)
                instance.getAge().then((age) => this.age = age)
            });
        },
        methods: {
            update() {
                return UserInfoContract.deployed()
                    .then((instance) => {
                        instance.setName(this.name, {from: this.account});
                        //instance.setAge(this.age, {from: this.account});
                    })
                    .catch((e) => {
                        console.error(e)
                    })
            },
        }
    }
</script>